<?php

declare(strict_types=1);

namespace app\service\system\file;

class ImageMerge
{
    public function image()
    {
        $url = '/home/wsy/Desktop';
        self::merge($url . '/' . time() . '.png', $url . '/bg.jpeg', $url . '/qr.png', '12536598');
    }
    /**
     * 图片合并
     * @param string $save_path 保存路径
     * @param string $bg_url 背景图路径
     * @param string $qr_url 二维码图路径
     * @param string $qrcode 推荐码
     */
    public static function merge($save_path, $bg_url, $qr_url, $qrcode = ''): void
    {
        //背景图
        $bgInfo = getimagesize($bg_url);
        $source_w = $bgInfo['0'];
        $bgImage = imagecreatefromstring(file_get_contents($bg_url));
        //二维码
        $qrInfo = getimagesize($qr_url);
        $qrImage = imagecreatefromstring(file_get_contents($qr_url));
        //合并
        $dstX = (int) floor(($source_w - $qrInfo['0']) / 2);
        imagecopyresampled($bgImage, $qrImage, $dstX, 410, 0, 0, 280, 280, imagesx($qrImage), imagesy($qrImage));
        //添加文字
        $font = root_path() . '/file/ttf/Alibaba-PuHuiTi-Light.ttf'; //字体
        $content = [$qrcode];
        $fontLposition = [210, 280]; //距左边距
        $fontTposition = [400, 460]; //距上边距
        if (count($content) > 0) {
            for ($i = 0; $i < count($content); $i++) {
                imagettftext($bgImage, 20, 0, $fontLposition[$i], $fontTposition[$i], 21, $font, $content[$i]);
            }
        }
        imagepng($bgImage, $save_path);
        //销毁
        imagedestroy($bgImage);
        imagedestroy($qrImage);
    }
}
